define([
    'require',
    'angular',
], function(require) {
    'use strict';
    angular
        .module('todoApp', [])
        .controller('tdCtrl', ['$scope', '$location', ($scope, $location) => {
            $scope.text = '';
            $scope.todos = [
                { id: 1, text: '吃饭', ok: false },
                { id: 2, text: '睡觉', ok: false },
                { id: 3, text: '学习', ok: true },
            ];

            let last = $scope.todos.sort((td1, td2) => {
                return td1.id - td2.id < 0;
            }).slice(0, 1)[0];
            $scope.add = () => {
                if (!$scope.text) return;
                $scope.todos.push({
                    id: last.id + 1,
                    text: $scope.text,
                    ok: false
                });
                $scope.text = '';
            };

            $scope.del = (id) => {
                for (let [key, value] of $scope.todos.entries()) {
                    if (value.id === id) {
                        $scope.todos.splice(key, 1);
                    }
                }
            };
            $scope.clear = () => {
                $scope.todos = $scope.todos
                    .filter(todo => todo.ok === false);
            };
            //
            $scope.isok = () => {
                return $scope.todos
                    .some(todo => todo.ok === true);
            };
            //$scope
            $scope.editing = -1;
            $scope.edit = (id) => {
                $scope.todos.forEach(todo => {
                    if (todo.id === id && !todo.ok) {
                        console.log(id);
                        $scope.editing = id;
                    }
                });
            };
            $scope.save = () => {
                $scope.editing = -1;
            };

            let all = true;
            $scope.toggleAll = () => {
                $scope.todos.forEach(todo => {
                    todo.ok = all;
                });
                all = !all;
            };
            $scope.okfilter = {};
            $scope.$location = $location;
            $scope.$watch('$location.path()', (now, old) => {
                switch (now) {
                    case '/completed':
                        $scope.okfilter = { ok: true };
                        break;
                    case '/active':
                        $scope.okfilter = { ok: false };
                        break;
                    default:
                        $scope.okfilter = {};
                        break;
                }
                // console.log(now, old);
            });
            //console.log($location.path());
        }])
});